package com.example.demo.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.demo.pojo.SysUser;
import com.example.demo.pojo.SysUserMap;

public class UserRealm  extends AuthorizingRealm {
	 private static final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);
	 
	 @Autowired 
	 private SysUserMap sysUsermap;
	 
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
		List<String> sysPermissions = sysUsermap.selectPermissionByUserId(sysUser.getUserId());
	    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(sysPermissions);
        LOGGER.info("doGetAuthorizationInfo");
        return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		 UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
	        SysUser sysUser = sysUsermap.findByUserName(token.getUsername());
	        if (sysUser == null) {
	            return null;
	        }
	        LOGGER.info("doGetAuthenticationInfo");
	        return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword().toCharArray(), ByteSource.Util.bytes(sysUser.getSalt()), getName());
	}

}
